Telegram Group & Telegram Channel
🧠 Хитрая задача на C++: "Исчезающее число среди строк"

Условие
Дан список строк, представляющих числа от 1 до 100 включительно. Одного числа нет.
Твоя задача — найти, какого именно числа не хватает.
Нельзя использовать сортировку, std::accumulate, std::unordered_map, std::stoi можно.

Пример:
Массив: ["1", "2", "3", ..., "98", "99"] (без "100")
Ответ: 100

Формат:


int findMissingNumber(const std::vector<std::string>& data);


Решение с XOR


#include <iostream>
#include <vector>
#include <string>

int findMissingNumber(const std::vector<std::string>& data) {
int xor_full = 0;
int xor_data = 0;

for (int i = 1; i <= 100; ++i) {
xor_full ^= i;
}

for (const auto& s : data) {
xor_data ^= std::stoi(s);
}

return xor_full ^ xor_data;
}


Пример использования:


int main() {
std::vector<std::string> data;
for (int i = 1; i <= 100; ++i) {
if (i != 57) { // Удалим 57
data.push_back(std::to_string(i));
}
}

std::cout << "Пропущено: " << findMissingNumber(data) << std::endl;
return 0;
}


Почему работает:
XOR — идеальное решение, когда нужно найти одну потерянную величину среди уникальных значений.
a ^ a = 0, 0 ^ b = b. Поэтому:
(XOR всех от 1 до 100) ^ (XOR из данных) = отсутствующее число.

@cpluspluc



tg-me.com/cpluspluc/1083
Create:
Last Update:

🧠 Хитрая задача на C++: "Исчезающее число среди строк"

Условие
Дан список строк, представляющих числа от 1 до 100 включительно. Одного числа нет.
Твоя задача — найти, какого именно числа не хватает.
Нельзя использовать сортировку, std::accumulate, std::unordered_map, std::stoi можно.

Пример:
Массив: ["1", "2", "3", ..., "98", "99"] (без "100")
Ответ: 100

Формат:


int findMissingNumber(const std::vector<std::string>& data);


Решение с XOR


#include <iostream>
#include <vector>
#include <string>

int findMissingNumber(const std::vector<std::string>& data) {
int xor_full = 0;
int xor_data = 0;

for (int i = 1; i <= 100; ++i) {
xor_full ^= i;
}

for (const auto& s : data) {
xor_data ^= std::stoi(s);
}

return xor_full ^ xor_data;
}


Пример использования:


int main() {
std::vector<std::string> data;
for (int i = 1; i <= 100; ++i) {
if (i != 57) { // Удалим 57
data.push_back(std::to_string(i));
}
}

std::cout << "Пропущено: " << findMissingNumber(data) << std::endl;
return 0;
}


Почему работает:
XOR — идеальное решение, когда нужно найти одну потерянную величину среди уникальных значений.
a ^ a = 0, 0 ^ b = b. Поэтому:
(XOR всех от 1 до 100) ^ (XOR из данных) = отсутствующее число.

@cpluspluc

BY C++ Academy


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/cpluspluc/1083

View MORE
Open in Telegram


C Academy Telegram | DID YOU KNOW?

Date: |

The SSE was the first modern stock exchange to open in China, with trading commencing in 1990. It has now grown to become the largest stock exchange in Asia and the third-largest in the world by market capitalization, which stood at RMB 50.6 trillion (US$7.8 trillion) as of September 2021. Stocks (both A-shares and B-shares), bonds, funds, and derivatives are traded on the exchange. The SEE has two trading boards, the Main Board and the Science and Technology Innovation Board, the latter more commonly known as the STAR Market. The Main Board mainly hosts large, well-established Chinese companies and lists both A-shares and B-shares.

The seemingly negative pandemic effects and resource/product shortages are encouraging and allowing organizations to innovate and change.The news of cash-rich organizations getting ready for the post-Covid growth economy is a sign of more than capital spending plans. Cash provides a cushion for risk-taking and a tool for growth.

C Academy from us


Telegram C++ Academy
FROM USA